import hmac
import base64
import time
import datetime
import pandas as pd
from functools import wraps
from . import consts as c

api_key = "024e27ad-8f4f-4fbf-968f-5a9465d373fd"
secret_key = "8255EDE49A52494B7A9284671D87BE03"
passphrase = "PLM121235plm"

# flag是实盘与模拟盘的切换参数 flag is the key parameter which can help you to change between demo and real trading.
# flag = '1'  # 模拟盘 demo trading
flag = '0'  # 实盘 real trading


def sign(message, secretKey):
    mac = hmac.new(bytes(secretKey, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256')
    d = mac.digest()
    return base64.b64encode(d)


def pre_hash(timestamp, method, request_path, body):
    return str(timestamp) + str.upper(method) + request_path + body


def get_header(api_key, sign, timestamp, passphrase, flag):
    header = dict()
    header[c.CONTENT_TYPE] = c.APPLICATION_JSON
    header[c.OK_ACCESS_KEY] = api_key
    header[c.OK_ACCESS_SIGN] = sign
    header[c.OK_ACCESS_TIMESTAMP] = str(timestamp)
    header[c.OK_ACCESS_PASSPHRASE] = passphrase
    header['x-simulated-trading'] = flag
    return header


def parse_params_to_str(params):
    url = '?'
    for key, value in params.items():
        url = url + str(key) + '=' + str(value) + '&'
    return url[0:-1]


def get_timestamp():
    now = datetime.datetime.utcnow()
    t = now.isoformat("T", "milliseconds")
    return t + "Z"


def signature(timestamp, method, request_path, body, secret_key):
    if str(body) == '{}' or str(body) == 'None':
        body = ''
    message = str(timestamp) + str.upper(method) + request_path + str(body)

    mac = hmac.new(bytes(secret_key, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256')
    d = mac.digest()

    return base64.b64encode(d)


def get_all_data(func):
    """
    默认获取北京时间的全部K线

    :param func: 需要被装饰的函数
    :return:
    """
    @wraps(func)
    def wrapper(*args, **kwargs):
        """
        the inner function
        :param args:
        :param kwargs: time_zone，str，需要获取的时区格式  '+0800'， '+0000'
        :return: func, the function being decorated
        """

        time_zone = kwargs.pop('time_zone', '+0800')
        end_date = kwargs['after']
        start_date = kwargs['before']

        if time_zone == '+0000':  # 如果是获取UTC时间，则需要对bar做一定的修改
            bar = kwargs['bar']
            if 'utc' not in bar:
                bar = bar + 'utc'
                kwargs.update({'bar': bar})

        temp_end_date = end_date
        all_df_list = []
        while(start_date < temp_end_date):
            kwargs.update({'after': temp_end_date})
            ans = func(*args, **kwargs)
            if ans['data']:  # 获取的数据不为空
                df = pd.DataFrame(ans['data'], columns=['timestamp', 'open', 'high', 'low', 'close', 'volume', 'amount'])
                all_df_list.append(df)
                temp_end_date = int(ans['data'][-1][0])
                time.sleep(0.15)
            else:    # 数据已经全部遍历完成
                break

        all_df = pd.concat(all_df_list, axis=0)

        # UTC时间转换为对应的时区
        # all_df['time_stamp'] = all_df.apply(lambda x: int(x['time_stamp'] / 1000), axis=1)  # 转换成秒
        all_df['end_date'] = pd.to_datetime(all_df['timestamp'], unit='ms').dt.tz_localize('UTC').dt.tz_convert(time_zone)
        all_df['end_date'] = all_df['end_date'].dt.strftime('%Y-%m-%d')
        all_df['datetime'] = pd.to_datetime(all_df['timestamp'], unit='ms').dt.tz_localize('UTC').dt.tz_convert(time_zone)
        all_df['datetime'] = all_df['datetime'].dt.strftime('%Y-%m-%d %H:%M:%S')
        all_df.drop_duplicates(subset=['timestamp'], inplace=True)
        all_df.set_index('end_date', inplace=True)
        all_df.sort_index(inplace=True)

        return all_df

    return wrapper